//
//  SDShopsTableViewController.m
//  Sydeny
//
//  Created by Rainbow on 7/23/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SDShopsTableViewController.h"
#import "Shop.h"
#import "ImageInfo.h"
#import "UtilHelper.h"
#import "ITSTableViewCell.h"
#import "SDShopDetailsViewController.h"
#import "SydenyAppDelegate.h"
#import "PersistenceData.h"

@implementation SDShopsTableViewController
@synthesize recommendTableView;
@synthesize recommandBgView;
@synthesize shops,listType,tableView;
@synthesize loadFinish;
@synthesize requestType;

- (id)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)dealloc
{
    [imageCache release];
    [shops release];
    [tableView release];
    [recommendTableView release];
    [recommandBgView release];
    [requestParams release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    loadFinish = YES;
    if (requestParams == nil) {
        requestParams = [[NSMutableDictionary alloc] init];
    }
    recommandBgView.layer.cornerRadius = 10;
    self.tableView.showsVerticalScrollIndicator = NO;
    shops = [[NSMutableArray alloc] init];
    imageCache = [[NSMutableDictionary alloc] init];
    [self.navigationController setNavigationBarHidden:NO];
    
    if (_refreshTableHeaderView == nil) {
		
		EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.tableView.bounds.size.height, self.view.frame.size.width, self.tableView.bounds.size.height)];
		view.delegate = self;
		[self.tableView addSubview:view];
		_refreshTableHeaderView = view;
		[view release];
	}
	
	//  update the last update date
	[_refreshTableHeaderView refreshLastUpdatedDate];
}

- (void)viewDidUnload
{
    [self setRecommendTableView:nil];
    [self setRecommandBgView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (loadFinish) {
        return [shops count]; 
    }
    return [shops count] + 1;
}

- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (!loadFinish && (indexPath.row == [self.shops count])) {
		UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];	
		cell.contentView.backgroundColor = [UIColor whiteColor];
		cell.textLabel.textAlignment = UITextAlignmentCenter;
		cell.textLabel.font = [UIFont systemFontOfSize:12];
		cell.textLabel.text = @"显示更多...";
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		return cell;
	}
    
    Shop *shop = [shops objectAtIndex:indexPath.row];
    NSString *imageName = nil;
    if ([shop.images count] > 0) {
        imageName = [shop.images objectAtIndex:0];
    }
    static NSString *CellIdentifier = @"Cell";
    
    ITSTableViewCell *cell = (ITSTableViewCell *)[_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[ITSTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier  stubImageName:@"160_120.png" imageCache:imageCache shop:shop index:indexPath.row imageRect:CGRectMake(10, 10, 80, 60)] autorelease];
    }
    [cell updateWithShop:shop imageCache:imageCache index:indexPath.row];
    // Configure the cell...
    
    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == [self.shops count]) {
        [self getMore];
        return;
    }
    Shop *shop = [self.shops objectAtIndex:indexPath.row];
    [[PersistenceData sharedData] addHistoryShop:shop];
    SDShopDetailsViewController *shopDetailsViewController = [[SDShopDetailsViewController alloc] initWithShop:shop];
    [self.navigationController pushViewController:shopDetailsViewController animated:YES];
    [shopDetailsViewController release];
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == [self.shops count]) {
        return 40;
    }
    return 80;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"table_header.png"]] autorelease];
    imageView.frame = CGRectMake(0, 0, 300, 20);
    return imageView;
}

#pragma mark -
#pragma mark Scroll view delegate


- (void)scrollViewDidScroll:(UIScrollView *)scrollView{	
	[_refreshTableHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
	[_refreshTableHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	if (loadFinish || loadingMore) {
		return;
	}
	CGPoint origin = scrollView.bounds.origin;
	if (scrollView.contentSize.height - origin.y <= self.view.bounds.size.height - 30) {
		[self getMore];
	}
}

-(void)getMore
{    
    if (loadingMore) {
        return;
    }
    UIActivityIndicatorView	*activiter = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
	[activiter startAnimating];
	activiter.frame = CGRectMake(80, 12, 20, 20);
	NSInteger count = [self.shops count];
	lastIndexPath = [NSIndexPath indexPathForRow:count inSection:0];
	[self.tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
	[self.tableView cellForRowAtIndexPath:lastIndexPath].textLabel.text = @"显示更多...";
	[[self.tableView cellForRowAtIndexPath:lastIndexPath] addSubview:activiter];
	[activiter release];
	
    loadingMore = YES;
	[requestParams setObject:[NSString stringWithFormat:@"%d",PER_PAGE_NUMBER] forKey:@"limit"];
	[requestParams setObject:[NSString stringWithFormat:@"%d",count/PER_PAGE_NUMBER + 1] forKey:@"page"];
	[[ServiceHelper sharedService] requestServerForMethod:self.requestType WithParameters:requestParams AndCallBackScope:self AndSuccessSel:@"getShopsSuccess:" AndFailedSel:@"getShopsFailed:"];
    
}


-(void)getShopsSuccess:(NSObject *)result
{
    loadingMore = NO;
    NSArray *shopDics = [(NSDictionary *)result objectForKey:@"shops"];
    if ([shopDics count] < PER_PAGE_NUMBER) {
        loadFinish = YES;
    }
    else
    {
        loadFinish = NO;
    }
    if (_reloading) {
        [shops removeAllObjects];
    }
    
    for (NSDictionary *shopDic in shopDics) {
        Shop *shop = [[Shop alloc] init];
        shop.shopId = [UtilHelper getStringValue:[shopDic objectForKey:@"shop_id"]];
        shop.title = [UtilHelper getStringValue:[shopDic objectForKey:@"title"]];
        shop.name = [UtilHelper getStringValue:[shopDic objectForKey:@"name"]];
        shop.address = [UtilHelper getStringValue:[shopDic objectForKey:@"address"]];
        shop.telephone = [UtilHelper getStringValue:[shopDic objectForKey:@"telephone"]];
        shop.createTime = [UtilHelper getStringValue:[shopDic objectForKey:@"createtime"]];
        shop.email = [UtilHelper getStringValue:[shopDic objectForKey:@"email"]];
        shop.latitude = [UtilHelper getStringValue:[shopDic objectForKey:@"latitude"]];
        shop.longtitude = [UtilHelper getStringValue:[shopDic objectForKey:@"longitude"]];
        shop.description = [UtilHelper getStringValue:[shopDic objectForKey:@"description"]];
        shop.details = [UtilHelper getStringValue:[shopDic objectForKey:@"details"]];
        NSArray *images = [shopDic objectForKey:@"images"];
        for (NSDictionary *imageInfoDic in images) {
            ImageInfo *imageInfo = [[ImageInfo alloc] init];
            imageInfo.imageId = [UtilHelper getStringValue:[imageInfoDic objectForKey:@"image_id"]];
            imageInfo.imageUrl = [UtilHelper getStringValue:[imageInfoDic objectForKey:@"imageurl"]];
            imageInfo.thumbImagUrl = [UtilHelper getStringValue:[imageInfoDic objectForKey:@"thumb_imageurl"]];
            [shop.images addObject:imageInfo];
            [imageInfo release];
        }
        [shops addObject:shop];
        [shop release];
    }
    [self.tableView reloadData];
    SydenyAppDelegate *appDelegate = (SydenyAppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate removeCoverView];
    if (_reloading) {
        [self performSelector:@selector(doneLoadingTableViewData)];
    }
}

-(void)getShopsFailed:(NSObject *)result
{
    if (_reloading) {
        [self performSelector:@selector(doneLoadingTableViewData)];
    }
}

-(void)AdvertisingDidSelectedWithShop:(Shop *)shop
{
    SDShopDetailsViewController *shopDetailsViewController = [[SDShopDetailsViewController alloc] initWithShop:shop];
    [self.navigationController pushViewController:shopDetailsViewController animated:YES];
    [shopDetailsViewController release];
}

- (void)reloadTableViewDataSource{
    [requestParams setObject:[NSString stringWithFormat:@"%d",PER_PAGE_NUMBER] forKey:@"limit"];
	[requestParams setObject:[NSString stringWithFormat:@"%d",1] forKey:@"page"];
	[[ServiceHelper sharedService] requestServerForMethod:self.requestType WithParameters:requestParams AndCallBackScope:self AndSuccessSel:@"getShopsSuccess:" AndFailedSel:@"getShopsFailed:"];
	_reloading = YES;
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
	[_refreshTableHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
}

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
	[self reloadTableViewDataSource];
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
	
	return _reloading; // should return if data source model is reloading
	
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
	return [NSDate date]; // should return date data source was last changed
	
}

@end
